<template>
  <div>
    <el-card>
      <!-- 头部的查询部分 -->
      <div slot="header" class="clearfix">
        <el-input
          v-model="searchforName"
          placeholder="用户名"
          style="width:200px;"
        ></el-input>
        <el-button
          type="primary"
          style="margin-left: 20px;height: 38px;"
          @click="searchUsername"
        >
          <i class="el-icon-search"></i> 查询</el-button
        >
        <el-button @click="resetInput">清空</el-button>
      </div>
      <p>
        <el-button
          type="primary"
          @click="showDialog({ username: '', nickName: '', password: '' })"
          >添加</el-button
        >
        <el-button type="danger" @click="deletes()">批量删除</el-button>
      </p>

      <!-- 表格部分 -->
      <el-table
        ref="multipleTable"
        :data="userList"
        border
        stripe
        tooltip-effect="dark"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="序号" width="80" type="index" align="center">
        </el-table-column>
        <el-table-column label="用户名" width="150" prop="username">
        </el-table-column>
        <el-table-column label="用户昵称" prop="nickName"> </el-table-column>
        <el-table-column label="角色列表" width="200" prop="roleName">
        </el-table-column>
        <el-table-column label="创建时间" width="180" prop="gmtCreate">
        </el-table-column>
        <el-table-column label="更新时间" width="180" prop="gmtModified">
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200" align="center">
          <template v-slot="{ row }">
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-start"
            >
              <el-button type="info" size="small" @click="handleClick(row)"
                ><i class="el-icon-user-solid"></i
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="修改用户"
              placement="top-start"
            >
              <el-button type="primary" size="small" @click="showDialog(row)"
                ><i class="el-icon-edit-outline"></i
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除用户"
              placement="top-start"
            >
              <el-button
                type="danger"
                size="small"
                @click="deleteUserByid(row.id)"
                ><i class="el-icon-delete"></i
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizechange"
        @current-change="currentchange"
        :current-page="current"
        :page-sizes="[5, 10, 20]"
        :page-size="limit"
        layout=" prev, pager, next, jumper, ->,sizes,total"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加和修改的dialog -->
    <el-dialog
      :title="`${saveForm.id ? '修改' : '添加'}用户`"
      :visible="isShowDialog"
      :before-close="handleClose"
    >
      <el-form
        :model="saveForm"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
        label-width="130px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="saveForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            placeholder="请输入用户昵称"
            v-model="saveForm.nickName"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-show="!saveForm.id">
          <el-input
            placeholder="请输入用户密码"
            v-model="saveForm.password"
          ></el-input>
        </el-form-item>
        <p style="padding-left: 860px;margin-top: 30px;">
          <el-button @click="resetForm('ruleForm')">取消</el-button>
          <el-button
            type="primary"
            style="margin-left: 20px;"
            @click="addOrUpdate('ruleForm')"
            >确定</el-button
          >
        </p>
      </el-form>
    </el-dialog>
    <!-- 获取用户角色列表 -->
    <el-dialog title="" :visible="roleDialogVisible" width="width">
      <el-form :model="roleInfo">
        <el-form-item label="用户名" size="small" label-width="80px">
          <el-input v-model="roleInfo.roleName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色列表" label-width="80px">
          <el-checkbox-group
            v-model="assignRolesNameList"
            @change="addAssignList"
          >
            <el-checkbox
              :label="item"
              v-for="item in allRolesNameList"
              :key="item"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// const cityOptions = [];
import {
  getUserPageListApi,
  saveUserApi,
  updateUserApi,
  removeUserApi,
  deletesUserApi,
  getRoleList,
  doAssign
} from "@/api/acl/user.js";
export default {
  name: "User",
  data() {
    return {
      /* 查询的相关数据 */
      current: 1,
      limit: 5,
      total: 0,
      userList: [],
      searchforName: "",

      /* 添加和修改相关数据 */
      isShowDialog: false,
      // 收集添加和修改的表单数据
      saveForm: {
        username: "",
        nickName: "",
        password: ""
      },

      multipleSelection: [],
      deleteIds: [],

      /* 分配角色相关的数据 */

      // 显示dialog的标识
      isShowRoleDialog: false,
      ////
      checkAll: true,
      allRolesList: [],
      assignRoles: [],
      allRolesListName: [],
      assignRolesName: [],
      citys: this.allRolesList,
      // 样式控制
      isIndeterminate: true,
      // 用户列表
      roleDialogVisible: false,
      roleInfo: {
        username: "",
        allRolesList: [],
        assignRoles: []
      },
      allRolesNameList: [],
      assignRolesNameList: [],
      assignRolesIdList: [],
      adminId: 0,

      // 校验规则
      rules: {
        username: [
          { required: true, message: "用户名是必填的", trigger: "blur" },
          { min: 3, max: 6, message: "长度在3-6个字符", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "用户昵称是必填的", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码是必填的", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 保存角色列表
    async saveRole() {
      // 整理数据
      this.assignRolesIdList = this.roleInfo.allRolesList.reduce((p, c) => {
        return this.assignRolesNameList.includes(c.roleName) ? [...p, c.id] : p;
      }, []);

      // 发请求
      await doAssign(this.adminId, this.assignRolesIdList);
      console.log(111);
      // 重新获取列表
      this.getList();
      // 关闭
      this.roleDialogVisible = false;
      this.$message.success("添加成功");
    },
    //获取选中的角色列表
    addAssignList(value) {
      this.assignRolesNameList = value;
      console.log(value, 3478474);
    },
    // 根据用户id获取角色列表
    async handleClick(row) {
      const result = await getRoleList(row.id);
      console.log(result);
      // 用户id
      this.adminId = row.id;
      this.roleDialogVisible = true;
      // 选项列表
      this.roleInfo.allRolesList = result.data.allRolesList;
      this.roleInfo.assignRoles = result.data.assignRoles;
      // 获取全部roleNAMW
      console.log(this.roleInfo.allRolesList);
      console.log(this.roleInfo.assignRoles);
      this.allRolesNameList = this.roleInfo.allRolesList.map(
        item => item.roleName
      );
      // 获取选中用户名
      this.assignRolesNameList = this.roleInfo.assignRoles.map(
        item => item.roleName
      );
      // 用户名
      this.roleInfo.roleName = row.username;
    },

    handleCheckAllChange(val) {
      this.allRolesList = val;
      console.log(val);
      // this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.assignRoles.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.assignRoles.length;
    },
    // 关闭分配角色的dialog
    handleCloseAsRole() {
      this.isShowRoleDialog = false;
    },
    // // 显示dialog和根据用户获取角色数据
    // async showRoleDialog(id) {
    //   this.isShowRoleDialog = true;
    //   const result = await getRoleList(id);
    //   // console.log(result);
    //   this.allRolesList = result.data.allRolesList;
    //   this.assignRoles = result.data.assignRoles;
    //   this.allRolesListName = this.allRolesList.map(item => {
    //     item.roleName;
    //   });
    //   // console.log(cityOptions);
    //   console.log(this.allRolesList);
    //   console.log(this.assignRoles);
    // },

    // 删除多个
    async deletes() {
      let arr = [];
      this.$refs.multipleTable.selection.forEach((Ele, index) => {
        arr.push(Ele.id);
        console.log(Ele.id);
      });
      console.log(arr);
      // 发送批量删除的请求
      await deletesUserApi(arr);
      // this.deleteIds = [];
      this.getList();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 删除单个用户信息
    deleteUserByid(id) {
      this.$confirm("确定要删除这条用户信息吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await removeUserApi(id);
          this.getList();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 关闭dialog
    handleClose() {
      this.isShowDialog = false;
    },
    // 确定按钮触发添加或修改的事件
    addOrUpdate(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.saveForm.id) {
            // console.log(111);
            await updateUserApi(this.saveForm);
            this.$message({
              message: "修改成功!",
              type: "success"
            });
          } else {
            // console.log(this.saveForm);
            await saveUserApi(this.saveForm);
            this.$message({
              message: "添加成功!",
              type: "success"
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });

      this.getList();
      // 关闭dialog
      this.isShowDialog = false;
    },
    // 添加和修改界面的取消按钮事件函数
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.isShowDialog = false;
    },
    // 显示dialog
    showDialog(us) {
      this.isShowDialog = true;
      this.saveForm = us;
    },

    // 清空搜索框
    resetInput() {
      this.searchforName = "";
      this.getList();
    },

    // 用户名模糊搜索
    async searchUsername() {
      const result = await getUserPageListApi(1, 1, {
        username: this.searchforName
      });
      // console.log(result);
      this.userList = result.data.items;
      this.searchforName = "";
    },
    // 分页组件触发的函数
    sizechange(val) {
      this.limit = val;
      this.getList();
    },
    currentchange(val) {
      this.current = val;
      this.getList();
    },
    // 获取用户信息分页列表
    async getList() {
      const result = await getUserPageListApi(this.current, this.limit);
      // console.log(result);
      this.userList = result.data.items;
      this.total = result.data.total;
    }
  },
  // 计算属性
  computed: {
    // allRolesNameList() {
    //   return this.roleInfo.allRolesList.map(item => item.roleName);
    // },
    allUserNameList() {
      return this.userList.map(item => item.username);
    }
  },
  mounted() {
    this.getList();
  }
};
</script>
<style></style>
